import { defineEventHandler, getQuery } from 'h3'
import redis from '../../util/redis'

export default defineEventHandler(async (event) => {
  try {
    const q = getQuery(event)
    const limit = Math.min(Number(q.limit) || 50, 500)
    const key = 'hand-speed:leaderboard'

    // ZRANGE with WITHSCORES returns [member, score, member, score, ...]
    const raw = await (redis as any).zrange(key, 0, limit - 1, 'WITHSCORES')

    const list: any[] = []
    for (let i = 0; i < raw.length; i += 2) {
      const member = raw[i]
      const score = raw[i + 1]
      try {
        const parsed = JSON.parse(member)
        parsed.interval = Number(score)
        list.push(parsed)
      } catch (e) {
        list.push({ name: member, interval: Number(score), id: member, ts: Date.now() })
      }
    }

    return list
  } catch (err: any) {
    event.node.res.statusCode = 500
    return { status: 500, error: String(err) }
  }
})
